package com.njit.postbar.adapter;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.njit.postbar.CircleDesc;
import com.njit.postbar.CreateCircle;
import com.njit.postbar.R;
import com.njit.postbar.model.Circle;
import com.njit.postbar.model.Hide;
import com.njit.postbar.model.Star;
import com.njit.postbar.model.User;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class CircleListAdapter extends BaseAdapter {

    private Context context;

    private List<?> list;

    private User user;
    //该用户收藏的所有的圈子的id
    private List<Integer> staredCircleIds;

    public CircleListAdapter(Context context, List<?> list,User user) {
        this.list = list;
        this.context = context;
        this.user = user;
        //该用户收藏的所有圈子
        List<Star> stars = new ArrayList<>();
        if(user!=null){
            stars = LitePal.where("targettype=? and userid=? and isstared = ?", Star.CIRCLE, user.getId() + "", "1").find(Star.class);
        }        staredCircleIds = new ArrayList<>();
        for (int i = 0; i< stars.size(); i++)
            staredCircleIds.add(stars.get(i).getTargetId());
    }
    /**
     * 组件集合
     * @author yuruiqiao
     */
    static final class Component{
        ImageView image,bookmark;
        TextView title;
        TextView synopsis;
    }

    @Override
    public int getCount() {
        return list.size();
    }
    /**
     * 获得某一位置的数据
     */
    @Override
    public Object getItem(int position) {
        return list.get(position);
    }
    /**
     * 获得唯一标识
     */
    @Override
    public long getItemId(int position) {
        return position;
    }

    @SuppressLint("InflateParams")
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final Component component;
        if(convertView == null){
            component = new Component();
            //获得组件,实例化组件
            convertView = LayoutInflater.from(context).inflate(R.layout.item_circle, null);
            component.image = convertView.findViewById(R.id.recommend_item_bg_image);
            component.title = convertView.findViewById(R.id.recommend_item_content);
            component.synopsis = convertView.findViewById(R.id.recommend_item_bottom);
            component.bookmark = convertView.findViewById(R.id.bookmark);
            convertView.setTag(component);
        }else{
            component=(Component)convertView.getTag();
        }
        //绑定数据
        final Circle currentCircle = (Circle) list.get(position);
        String preImage = currentCircle.getPreviewImageUrl();
        //如果没有头像,用默认头像
        if("".equals(preImage)){
            Glide.with(context).load("http://yun918.cn/study/public/uploadfiles/img/Screenshot_20200608_010509.jpg").into(component.image);
        }else {
            Glide.with(context).load(preImage).into(component.image);
        }
        component.title.setText(currentCircle.getTitle());
        component.synopsis.setText(currentCircle.getSynopsis());

        if(staredCircleIds.contains(currentCircle.getId())){
            component.bookmark.setVisibility(View.VISIBLE);
        }else{
            component.bookmark.setVisibility(View.INVISIBLE);
        }

        //长按监听器
        convertView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if(user==null){
                    showDialog("提示","请先登录😅");
                }else {
                    listDialog(currentCircle.getId(),new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if(which==0){
                                if(user.getId() == currentCircle.getUserId()){
                                    //这里写修改
                                    Intent intent = new Intent(context, CreateCircle.class);
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable("user",user);
                                    bundle.putSerializable("circle",currentCircle);
                                    intent.putExtras(bundle);
                                    context.startActivity(intent);
                                }else{
                                    //已经被收藏了
                                    if(staredCircleIds.contains(currentCircle.getId())){
                                        Star star = LitePal.find(Star.class,currentCircle.getId());
                                        star.setIsStared(false);
                                        star.save();
                                        showDialog("提示","已取消收藏");
                                    }else{
                                        //这里写收藏star
                                        Star star = new Star();
                                        star.setUserId(user.getId());
                                        star.setTargetType(Star.CIRCLE);
                                        star.setTargetId(currentCircle.getId());
                                        star.setIsStared(true);
                                        star.save();
                                        showDialog("来自用户","感谢收藏😚😚😚");
                                    }
                                }
                            }else{
                                if(user.getId() == currentCircle.getUserId()){
                                    confirmDialog("真的要删除我嘛😭？",new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            //这里写删除
                                            LitePal.delete(Circle.class,currentCircle.getId());
                                            showDialog("提示","删除成功");
                                        }
                                    });
                                }else{
                                    if(staredCircleIds.contains(currentCircle.getId())){
                                        showDialog("提示","请先取消收藏");
                                    }else{
                                        confirmDialog("真的要隐藏我嘛😭？",new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                //这里写隐藏
                                                Hide hide = new Hide();
                                                hide.setTargetType(Hide.CIRCLE);
                                                hide.setTargetId(currentCircle.getId());
                                                hide.setState(true);
                                                hide.save();
                                                showDialog("提示","隐藏成功");
                                            }
                                        });
                                    }
                                }
                            }
                        }
                    }, currentCircle.getUserId());
                }
                return false;
            }
        });

        //点击事件
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转详情页
                Intent intent = new Intent(context, CircleDesc.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("user",user);
                bundle.putSerializable("circle",currentCircle);
                intent.putExtras(bundle);
                context.startActivity(intent);
            }
        });

        return convertView;
    }
    /**
     *@author yuruiqiao
     *@date 2020/6/6
     *@description 列表确认框
     */
    private void listDialog(int circleId,DialogInterface.OnClickListener listener,int masterId){
        AlertDialog.Builder builder  = new AlertDialog.Builder(context);
        builder.setTitle("提示框");
        if(user.getId()==masterId){
            builder.setItems(new String[]{"修改", "删除"}, listener);
        }
        else{
            if(staredCircleIds.contains(circleId)){
                builder.setItems(new String[]{"取消收藏", "隐藏"}, listener);
            }else{
                builder.setItems(new String[]{"收藏", "隐藏"}, listener);
            }
        }
        builder.show();
    }
    /**
     *@author yuruiqiao
     *@date 2020/6/6
     *@description 提示框
     */
    private void showDialog(String title,String message){
        AlertDialog.Builder builder  = new AlertDialog.Builder(context);
        builder.setTitle(title) ;
        builder.setMessage(message) ;
        builder.setPositiveButton("是" ,  null);
        builder.show();
    }
    /**
     *@author yuruiqiao
     *@date 2020/6/6
     *@description 选择确认框
     */
    private void confirmDialog(String message,DialogInterface.OnClickListener listener){
        AlertDialog.Builder builder  = new AlertDialog.Builder(context);
        builder.setTitle("提示") ;
        builder.setMessage(message) ;
        builder.setPositiveButton("是",listener);
        builder.setNegativeButton("否",null);
        builder.show();
    }
}
